package baiqitun.stupro.api.exception;

import baiqitun.stupro.common.exception.support.NotFoundException;
import baiqitun.stupro.common.exception.StuproException;
import baiqitun.stupro.common.model.Result;
import baiqitun.stupro.common.util.ResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

/**
 * @author kedaji
 * 异常处理器
 */
@Api("全局异常处理器")
@Slf4j
@RestControllerAdvice
public class SysExceptionHandler {

    @ApiOperation("处理数据校验异常")
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(ConstraintViolationException.class)
    public Result<?> handleNotFoundException(ConstraintViolationException e){
        //TODO 将日志写入MongoDB中
        log.info(e.getMessage(), e);
        return ResultUtil.error(e);
    }
    /**
     * 处理404异常
     * @param e 资源未找到异常
     * @return 404异常信息
     */
    @ApiOperation("处理404异常")
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ExceptionHandler(NotFoundException.class)
    public Result<?> handleNotFoundException(NotFoundException e){
        //TODO 将日志写入MongoDB中
        log.info(e.getMessage(), e);
        return ResultUtil.error(e);
    }
    /**
     * 处理自定义异常
     * @param e 异常对象
     * @return 异常信息
     */
    @ApiOperation("处理系统可处理的其他异常")
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(StuproException.class)
    public Result<?> handleStuproException(StuproException e){
        //TODO 将日志写入MongoDB中
        log.error(e.getMessage(), e);
        return ResultUtil.error(e);
    }

    /**
     * 处理未知异常
     * @param e 异常对象
     * @return 异常信息
     */
    @ApiOperation("处理其他未知异常")
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public Result<?> handleException(Exception e){
        //TODO 日志写入MangoDB中
        log.error(e.getMessage(), e);
        return ResultUtil.error(e);
    }
}
